package com.itany.cloud.controller;

import com.itany.cloud.entity.User;
import com.itany.cloud.util.ResponseResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:shixiaojun@itany.com
 * Date: 2022/3/21 9:44
 * Version: 1.0-SNAPSHOT
 */
@RestController
@RequestMapping("/users")
public class UserController {

    static Map<Integer,User> users = new HashMap<Integer,User>();
    static Integer id = 1;

    @GetMapping
    public ResponseResult findAll(){
        List<User> list = new ArrayList<>(users.values());
        return ResponseResult.success(list);
    }

    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id){
//        int i = 1/0;
        User user = users.get(id);
//        User user = new User(8001,"8001","8001","8001","8001");
        return ResponseResult.success(user);
    }

    @PostMapping
    public ResponseResult addUser(User user){
        // 模拟主键自增
        user.setId(id++);
        users.put(user.getId(),user);
        return ResponseResult.success();
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable("id") Integer id){
        users.remove(id);
        return ResponseResult.success();
    }

    @PutMapping
    public ResponseResult modifyUser(User user){
//        users.put(user.getId(),user);
        User u = users.get(user.getId());
        u.setUsername(user.getUsername());
        u.setPassword(user.getPassword());
        u.setPhone(user.getPhone());
        u.setAddress(user.getAddress());
        return ResponseResult.success();
    }


}
